package com.zhenyi.limian.index;

import org.hashids.Hashids;

import com.cenjiawen.common.IndexController;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.limian.common.model.LmMsg;
import com.zhenyi.limian.core.LMInterceptro;

@Before(LMInterceptro.class)
public class HomeController extends IndexController {

	private Hashids hashid = new Hashids("limian", 6);

	@Override
	public void index() {
		super.index();
		LmMsg msg = new LmMsg();
		msg.save();
		String code = hashid.encode(msg.getId());
		msg.setCode(code);
		setAttr("code", code);
		msg.update();
		render("/lm/index.html");
	}

	public void edit() {
		super.info();
		LmMsg msg = new LmMsg();
		msg.save();
		String code = hashid.encode(msg.getId());
		msg.setCode(code);
		msg.update();
		setInfoItem(msg);
		render("/lm/edit.html");
	}

	public void view() {
		String code = getPara(0);
		Long id = hashid.decode(code)[0];
		LmMsg msg = LmMsg.dao.findById(id);
		setInfoItem(msg);
		if (StrKit.notBlank(msg.getContent(), msg.getFromName())) {
			render("/lm/view.html");
			return;
		}
		render("/lm/edit.html");
	}

	@Override
	public void submit() {
		String code = getPara("code");
		String fromName = getPara("fromName");
		String toName = getPara("toName");
		String content = getPara("content");
		Integer type = getParaToInt("type");
		Long id = hashid.decode(code)[0];
		LmMsg msg = LmMsg.dao.findById(id);
		msg.setFromName(fromName);
		msg.setToName(toName);
		msg.setContent(content);
		msg.setType(type);
		msg.update();
		renderSuccess();
	}
}
